#include "TCPserver.hpp"
#include <memory>
#include "Daemon.hpp"

Response cal(Request request)
{
    int code = 0, result = 0;
    switch (request._op)
    {
    case '+':
        result = request._x + request._y;
        break;
    case '-':
        result = request._x - request._y;
        break;
    case '*':
        result = request._x * request._y;
        break;
    case '/':
        if (request._y == 0)
        {
            code = 1;
        }
        else
            result = request._x / request._y;
        break;
    case '%':
        if (request._y == 0)
        {
            code = 2;
        }
        else
            result = request._x % request._y;
        break;
    default:
        code = 3;
        break;
    }
    Response response(result, code);
    return response;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cout << "usage: " << argv[0] << " port" << std::endl;
        exit(1);
    }

    MyDaemon(); // 守护进程

    // 创建服务器
    std::unique_ptr<TCPServer> tcpSer(new TCPServer(atoi(argv[1])));
    int listen_sock = tcpSer->Init(); // 服务器初始化
    tcpSer->BindService(cal);         // 给服务器绑定具体任务
    tcpSer->Start(listen_sock);       // 运行服务器

    return 0;
}